package model.bs;
import model.entities.*;
import model.dao.*;
import java.sql.*;
import java.util.ArrayList;
public class ChatView {
	public void insertMessage(ChatClass c){
		Connection con=null;
		Statement stm=null;
		String query=null;
		int x=0;
		try{
			query="insert into chat(id,sender,ipaddress,timestamp,message) values("+c.getId()+",'"+c.getSender()+"','"+c.getIpaddress()+"','"+c.getTimestamp()+"','"+c.getMessage()+"')";
			System.out.println(query);
			con=new ConnectDb().doConnect();
			stm=con.createStatement();
			x=stm.executeUpdate(query);
			if(x==1){
				System.out.println("Succesfully Inserted");
			}
			else
				System.out.println("Insertion Failed");
			con.close();
		}
		catch(Exception e){
			System.out.println(e.getMessage());
		}
	}
	public ArrayList<ChatClass> getAllMessages(){
		//Returns arraylist of all messages
		Connection con=null;
		Statement stm=null;
		String query=null;
		ResultSet rst=null;
		ArrayList<ChatClass> allM=new ArrayList<ChatClass>();
		try{
			query="select id,sender,timestamp,ipaddress,message from chat order by timestamp desc";
			System.out.println(query);
			con=new ConnectDb().doConnect();
			stm=con.createStatement();
			rst=stm.executeQuery(query);
			while(rst.next()){
				System.out.println("Counting");
				allM.add(new ChatClass(rst.getInt(1), rst.getString(2), rst.getString(3), rst.getString(4), rst.getString(5)));
			}
			con.close();
		}
				catch(Exception e){
			System.out.println(e.getMessage());
		}
		
		return allM;
	}

	public int generateChatId(){
		Connection con=null;
		Statement stm=null;
		String query=null;
		ResultSet rst=null;
		int x=0;
		try{
			query="select chatid.nextval from dual";
			con=new ConnectDb().doConnect();
			stm=con.createStatement();
			rst=stm.executeQuery(query);
			while(rst.next()){
				x=rst.getInt(1);
			}
			con.close();
		}catch(Exception e){
			System.out.println(e.getMessage());
		}	
		
		return x;
	}
}